package formatter;

import java.util.HashMap;

import logging.LoggerConstants;
import logging.Record;
import Exception.InvalidFormatException;
import Exception.InvalidTypeFormatException;

public class FormatterTrad extends AbstractFormatter implements IFormatter {

	String format;

	public String getFormat() {
		return this.format;
	}

	private boolean isTRAD(String tipeFormat) {
		return (LoggerConstants.typeFormatDefault.equals(tipeFormat));
	}

	private void validateFormat(String typeFormat) throws InvalidFormatException {
		if (!isTRAD(typeFormat))
			throw new InvalidFormatException(typeFormat);
	}

	public FormatterTrad(String format) {
		this.format = format;
		this.typeFormat = LoggerConstants.typeFormatDefault;
		this.mapPattern = new HashMap<String, MessagePattern>();
	}

	protected String[] getPatterns() {
		return this.format.split("\\" + LoggerConstants.separatorDefault);
	}

	public String applyFormat(Record dataRecord) throws InvalidTypeFormatException,
			InvalidFormatException {
		String output = "";
		if (LoggerConstants.typeFormatDefault.equals(dataRecord.getTypeFormat())) {
			this.validateFormat(dataRecord.getTypeFormat());
			this.setMap(dataRecord, this.getPatterns());
			String[] patterns = this.getPatterns();
			for (String pattern : patterns) {
				if (pattern.contains(LoggerConstants.patternDate))
					output += this.mapPattern.get(LoggerConstants.patternDate).applyPattern();
				else
					output += this.mapPattern.get(pattern).applyPattern();

				if (!LoggerConstants.separatorDefault.equals(" "))
					output += " " + LoggerConstants.separatorDefault + " ";
				else
					output += LoggerConstants.separatorDefault;
			}
			if (output.endsWith("- "))
				return output.substring(0, output.length() - 3);
			return output.trim();
		} else if (this.chainFormatter != null) {
			return this.chainFormatter.applyFormat(dataRecord);
		} else
			throw new InvalidTypeFormatException(dataRecord.getLevel().toString());
	}

	public String getType() {
		return this.typeFormat;
	}

}
